from info import db, constants
from info.constants import QINIU_DOMIN_PREFIX, USER_COLLECTION_MAX_NEWS
from info.models import Category, News
from info.response_code import RET
from info.utils.common import login_user_data, send_pic
from . import profile_blu
from flask import render_template, g, redirect, request, jsonify, session


# 添加一个关注的路由
@profile_blu.route('/user_follower')
@login_user_data
def user_follower():
    # 要有分页
    # 获取页码
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg='参数有问题')
    # 将关注的用户进行分页
    user = g.user
    paginate = user.followed.paginate(p, USER_COLLECTION_MAX_NEWS, False)
    # 分页数据
    # 当前页
    follows = paginate.items
    # 当前页码
    current_page = paginate.page
    # 总页数
    total_page = paginate.pages
    data = {
        "follows": follows,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template('news/user_follow.html', data=data)


# 创建一个用户已发布新闻的路由
@profile_blu.route('/news_list')
@login_user_data
def news_list():
    # 获取页码
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg='参数有问题')

    # 当前用户发布了那些新闻
    user = g.user
    paginate = News.query.filter(News.user_id == user.id) \
        .paginate(p, USER_COLLECTION_MAX_NEWS, False)
    # 分页数据
    # 当前页
    news_li = paginate.items
    # 当前页码
    current_page = paginate.page
    # 总页数
    total_page = paginate.pages
    # 需要将分页数据转换
    news_dic_li = []
    for n_dic in news_li:
        news_dic_li.append(n_dic.to_review_dict())
    data = {
        "news_list": news_dic_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template('news/user_news_list.html', data=data)


# 创建一个发布新闻的路由
@profile_blu.route('/news_release', methods=['POST', 'GET'])
@login_user_data
def news_release():
    # 在get请求时候还需要获取分类的新闻分类信息
    if request.method == 'GET':
        # 需要分类信息
        categorys = Category.query.all()
        return render_template('news/user_news_release.html', categorys=categorys)
    else:
        # 如果是post阶段就获取参数
        '''
        title	string	是	新闻标题
        category_id	int	是	新闻分类_id
        digest	string	是	新闻摘要
        index_image	file	是	索引图片
        content
        '''
        title = request.form.get('title')
        category_id = request.form.get('category_id')
        digest = request.form.get('digest')
        content = request.form.get('content')
        # 获取图片
        index_image = request.files.get('index_image')
        # 判断参数是否存在
        if not all([title, category_id, digest, content, index_image]):
            return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
        # 检查图片是否能转成字节流
        try:
            index_image = index_image.read()
        except Exception as e:
            return jsonify(errno=RET.PARAMERR, errmsg='图片参数有误')
        # 把图片获取到传给七牛云 result_ret图片在网上的唯一值
        result_ret = None
        try:
            result_ret = send_pic(index_image)
        except Exception as e:
            return jsonify(errno=RET.PARAMERR, errmsg='请重新提交图片')
            print(e)
        # 将新闻添加到数据库中
        news_dict = News()
        news_dict.title = title
        news_dict.digest = digest
        news_dict.category_id = category_id
        news_dict.index_image_url = constants.QINIU_DOMIN_PREFIX + result_ret['key']
        news_dict.content = content
        # 添加新闻需要有个状态 0 == 审核通过 1审核不通过 2正在审核
        news_dict.status = 0
        # 还缺少两个参数
        news_dict.source = '个人新闻'
        news_dict.user_id = g.user.id
        db.session.add(news_dict)
        try:
            db.session.commit()
        except Exception as e:
            print(e)
    return jsonify(errno=RET.OK, errmsg='上传新闻成功')


# 创建一个收藏的路由
@profile_blu.route('/collection')
@login_user_data
def collection():
    # 当前页数
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    # 不会有post提交数据 只会有get提交 request.args
    # 针对当前用户的所有收藏
    user = g.user
    # 针对当前的收藏做分页 page当前页面 显示的页数
    paginate = user.collection_news.paginate(p, USER_COLLECTION_MAX_NEWS, False)
    # 当前页面
    collections = paginate.items
    # 当前页码
    current_page = paginate.page
    # 总页数
    total_page = paginate.pages

    # 将也分页的数据转换一下
    collection_dict_li = []
    for c1 in collections:
        collection_dict_li.append(c1.to_basic_dict())
    data = {
        'total_page': total_page,
        'current_page': current_page,
        'collections': collection_dict_li
    }
    return render_template('news/user_collection.html', data=data)


# 创建一个修改密码的路由
@profile_blu.route('/pass_info', methods=['POST', 'GET'])
@login_user_data
def pass_info():
    # method ==GET 显示页面
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    else:
        # 如果为post就处理页面请求
        '''
        old_password	string	是	旧密码
        new_password
        '''
        req_dict = request.json
        if not req_dict:
            return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
        # 判断参数不为空
        old_password = req_dict.get('old_password')
        new_password = req_dict.get('new_password')
        if not old_password:
            return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
        if not new_password:
            return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
        # 判断以前的密码和登录密码是否相同
        user = g.user
        if not user.check_password(old_password):
            return jsonify(errno=RET.PARAMERR, errmsg='现有密码和登录密码不一致')
        # 存储新密码
        user.password = new_password
        db.session.commit()
        return jsonify(errno=RET.OK, errmsg='修改密码成功')


# 创建一个头像修改的路由
@profile_blu.route('/pic_info', methods=['POST', 'GET'])
@login_user_data
def pic_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pic_info.html')
    else:
        # 通过post请求获取数据
        avatar_file = request.files.get('avatar')
        if not avatar_file:
            return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
            # 将头像传给七牛云
        result_ret = send_pic(avatar_file.read())
        # 七牛云会返回一个ret ret中包含了一个key result_ret.key
        # 将七牛云的key存储到mysql中
        user.avatar_url = QINIU_DOMIN_PREFIX + result_ret['key']
        db.session.commit()
        # 将结果返回给浏览器
        return jsonify(errno=RET.OK, errmsg='上传图片成功', avatar_url=user.avatar_url)


# 创建一个修改基本资料的路由
# 由原有的static/news/html/user_base_info.html -> user/base_info
@profile_blu.route('/base_info', methods=['POST', 'GET'])
@login_user_data
def base_info():
    # 获取当前页面中seesion数据->login_user_data g.user
    user = g.user
    if request.method == 'GET':
        # 如果是get的时候就显示页面
        # 判断如果user不存在 让用户返回到首页
        if not user:
            return redirect('/')
        return render_template('news/user_base_info.html', user=user)
    else:
        # 如果是post提交就是修改数据
        '''
        nick_name	string	是	昵称
        signature	string	是	签名
        gender	string	是	性别, MAN / WOMEN
        '''
        req_dict = request.json
        # 对数据的判断
        if not req_dict:
            return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')

        nick_name = req_dict.get('nick_name')
        signature = req_dict.get('signature')
        gender = req_dict.get('gender')
        # 判断 nick_name 和gender不能为空
        if not nick_name:
            return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
        if not gender:
            return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
        # 判断gender只能MAN  或 WOMAN
        if gender not in ('MAN', 'WOMAN'):
            return jsonify(errno=RET.PARAMERR, errmsg='性别参数错误')
        # 修改user
        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender
        db.session.commit()
        # session
        session['nick_name'] = nick_name
        # 返回操作结果
        return jsonify(errno=RET.OK, errmsg='修改成功')


# 添加用户的基础页面
# 127.0.0.1/user/basic
@profile_blu.route('/basic')
@login_user_data
def basic():
    user = g.user
    # 判断如果user不存在 让用户返回到首页
    if not user:
        return redirect('/')

    return render_template('news/user.html', user=user)
